<template>
  <n-modal
    v-model:show="dialogVisible"
    preset="dialog"
    :title="editData?.id ? '编辑' : '新增'"
    positive-text="确认"
    negative-text="取消"
    @positive-click="editOk"
    @negative-click="dialogVisible = false"
    style="width: 100%"
  >
    <el-form
      :model="editData"
      ref="form"
      :rules="{
        name: { required: true, message: '必填', trigger: 'blur' },
      }"
    >
      <el-form-item label="名称" label-width="100" prop="name">
        <el-input v-model="editData.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="链接" label-width="100">
        <n-input
          v-model:value="editData.url"
          autocomplete="off"
          placeholder="请输入链接"
          style="--n-padding-right: 0"
        >
          <template #suffix><n-button @click="openUrl(editData.url)">打开</n-button></template>
        </n-input>
      </el-form-item>
      <el-form-item label="图标" label-width="100">
        <n-input v-model:value="editData.ico" placeholder="自定义图标" style="--n-padding-right: 0">
          <template #suffix>
            <SiteIcon :icon="editData.ico" />
            <n-button @click="openUrl('https://icon-sets.iconify.design/?query=' + editData.name)">
              去挑选
            </n-button>
          </template>
        </n-input>
      </el-form-item>
      <el-form-item label="分类标签" label-width="100">
        <n-select
          v-model:value="editData.tags"
          filterable
          multiple
          tag
          :options="sitesStore.tags"
          label-field="name"
          value-field="key"
          placeholder="选择分类标签"
          :on-create="createTag"
          @update-value="updateTags"
        />
      </el-form-item>
      <el-form-item label="描述" label-width="100">
        <el-input v-model="editData.explain" autocomplete="off" />
      </el-form-item>

      <el-divider>子链接</el-divider>
      <el-card v-for="(item, index) in editData.children" :key="item.id" style="margin: 20px">
        <template #header>
          <el-button text v-if="index !== 0" @click="move(index, index - 1)">上移</el-button>
          <el-button
            text
            v-if="index !== editData.children.length - 1"
            @click="move(index, index + 1)"
          >
            下移
          </el-button>
          <el-button text @click="deletChild(index)">删除</el-button>
        </template>
        <el-form-item label="名称">
          <el-input v-model="item.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="item.url" autocomplete="off">
            <template #append><el-button @click="openUrl(item.url)">打开</el-button></template>
          </el-input>
        </el-form-item>
      </el-card>

      <div style="text-align: center">
        <el-button @click="addChildren">
          <Icon icon="material-symbols:add-circle-outline" width="20" />
        </el-button>
      </div>
    </el-form>
  </n-modal>
</template>
<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { ref, watch } from 'vue'
import { useSites } from '@/stores/sites'
import { v4 as uuidv4 } from 'uuid'
import SiteIcon from '@/components/SiteIcon.vue'
const props = defineProps({
  data: Object,
})

const editData = ref()
const dialogVisible = ref(false)
watch(
  () => props.data,
  (val) => {
    editData.value = val
    dialogVisible.value = !!editData.value
  },
)

const createTag = (label: string) => ({
  key: uuidv4(),
  name: label,
})
let selectedTags: { key: string; name: string }[]
const updateTags = (val: any, options: { key: string; name: string }[]) => {
  selectedTags = options
}
const saveTags = async () => {
  const tags = [...sitesStore.tags]
  let needSave = false
  selectedTags?.forEach((selectedItem) => {
    const index = tags.findIndex((item) => item.key === selectedItem.key)
    if (index === -1) {
      tags.push(selectedItem)
      needSave = true
    }
  })
  if (needSave) {
    return sitesStore.setTags(tags)
  }
}

function addChildren() {
  if (!editData.value.children) {
    editData.value.children = []
  }
  editData.value.children.push({
    id: uuidv4(),
  })
}
function move(index: number, target: number) {
  const children = editData.value.children
  const temp = children[index]
  children[index] = children[target]
  children[target] = temp
}
function deletChild(index: number) {
  editData.value.children.splice(index, 1)
}

const sitesStore = useSites()
const form = ref()
function editOk() {
  form.value.validate(async (valid: any) => {
    if (!valid) return
    await saveTags()

    const urls = [...sitesStore.sites]
    const index = urls.findIndex((item) => item.id === editData.value.id)
    if (index !== -1) {
      urls[index] = editData.value
    } else {
      urls.push({
        ...editData.value,
        id: uuidv4(),
      })
    }
    sitesStore.setSites(urls).then(() => {
      dialogVisible.value = false
    })
  })
}

function openUrl(url: string | URL | undefined) {
  window.open(url)
}
</script>
